import { constantRouterMap } from '@/router'
import Layout from '@/views/layout/Layout'
const _import = require('@/router/_import_' + process.env.NODE_ENV)

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { menus } = data
        const accessedRouters = []
        menus.forEach((v) => {
          const children = []
          if (v.children) {
            v.children.forEach((vv) => {
              const auth = []
              if (vv.auth) {
                vv.auth.forEach((vvv) => {
                  auth.push(vvv.path)
                })
              }
              children.push({
                path: vv.path,
                component: _import(v.path + '/' + vv.path),
                name: vv.name,
                meta: {
                  title: vv.title,
                  noCache: true,
                  auth: auth
                }
              })
            })
          }
          accessedRouters.push({
            path: '/' + v.path,
            component: Layout,
            redirect: 'noredirect',
            name: v.name,
            meta: {
              title: v.title,
              icon: v.icon
            },
            children: children
          })
        })
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
